#ifndef __WEBSERVER_H__
#define __WEBSERVER_H__

#include <memory>
#include <unordered_map>
#include <glog/logging.h>

#include <unistd.h>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "../epoller/epoller.h"
#include "../http/httpconn.h"
#include "../timer/heaptimer.h"
#include "../pool/threadpool.h"


class WebServer{
public:
    WebServer(int port, bool trigMode, int timeoutMS, bool optLinger, int threadNum);
    ~WebServer();
    void Start();

private:
    static const int MAX_FD = 65536;

    int SetNonblock(int fd);
    void InitEventMode(int trigMode);
    bool InitSocket();

    void DealListen();
    void CloseConn(HttpConn* conn);
    void DealRead(HttpConn* conn);
    void DealWrite(HttpConn* conn);

    void SendError(int fd, const char* msg);
    void AddClient(int fd, sockaddr_in addr);

    void OnRead(HttpConn* conn);
    void OnWrite(HttpConn* conn);
    void OnProcess(HttpConn* conn);

    void ExtentTime(HttpConn* conn);

    int port_;
    bool openLinger_;
    int timeoutMS_;
    bool isClose_;
    int listenFd_;
    char* srcDir_;

    uint32_t listenEvent_;
    uint32_t connEvent_;

    std::unique_ptr<ThreadPool> threadPool_;
    std::unique_ptr<Epoller> epoller_;
    std::unique_ptr<HeapTimer> heapTimer_;
    std::unordered_map<int, HttpConn> users_;
};

#endif /* __WEBSERVER_H__ */
